import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 言初
 * Date: 2024-05-10
 * Time: 10:46
 */
// 写进程 加锁
public class write2 {
    private static RandomAccessFile raf;
    public void func(int writenums,int readnums) throws Exception {
        //获取随机存取文件对象，建立文件和内存的映射，即时双向同步
        raf = new RandomAccessFile("E:/test.txt", "rw");
        FileChannel fc = raf.getChannel();      //获取文件通道
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);  //获取共享内存缓冲区
        FileLock flock=null;

        for(int i=48;i<=57;i++){
            //阻塞独占锁，当文件锁不可用时，当前进程会被挂起
            flock=fc.lock();
            System.out.println(System.currentTimeMillis() +  ":write2:" + (char)i);
            mbb.put((byte)i);  //从文件第一个字节位置开始写入数据
            flock.release();        //释放锁
            Thread.sleep(1000);
        }
    }
}
